package com.qu.waibao.account;

import android.Manifest;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.mobileim.IYWLoginService;
import com.alibaba.mobileim.YWAPI;
import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.YWLoginParam;
import com.alibaba.mobileim.channel.event.IWxCallback;
import com.baidu.location.BDLocation;
import com.qu.waibao.AppConfig;
import com.qu.waibao.AppManager;
import com.qu.waibao.MainActivity;
import com.qu.waibao.R;
import com.qu.waibao.baidu.LocationUtils;
import com.qu.waibao.base.BaseActivity;
import com.qu.waibao.bean.ThirdLoginBean;
import com.qu.waibao.interf.XnetCallBack;
import com.qu.waibao.my.activity.XiuAuthenticActivity;
import com.qu.waibao.network.ActionUtil;
import com.qu.waibao.network.NetManager;
import com.qu.waibao.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import info.wangchen.simplehud.SimpleHUD;

public class LoginActivity extends BaseActivity implements View.OnClickListener,PlatformActionListener,
        LocationUtils.ILocateDelegate {
    /**
     * 10000000000  1(车主)
     * 10000000001  2(商家)
     * 10000000002  3(修理工)
     */
    private static final int REQUESTCODE = 0;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.iv_publish)
    ImageView iv_publish;
    @BindView(R.id.cb_check)
    CheckBox cb_check;
    @BindView(R.id.cb_pass)
    CheckBox cb_pass;
    @BindView(R.id.et_pass)
    EditText et_pass;
    @BindView(R.id.et_phone)
    EditText et_phone;
    private Intent intent;
    private int flag = 3;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ThirdLoginBean thirdLoginBean = (ThirdLoginBean) msg.obj;
            userThirdloginSet(thirdLoginBean,flag);
        }
    };
    private boolean isLocation = false;

    @Override
    protected int getContentView() {
        return R.layout.activity_login;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        tv_title.setText("登录");
        iv_publish.setVisibility(View.GONE);
        boolean isPass = AppConfig.getBoolean("isPass");
        if(isPass){
            String user = AppConfig.getString("user");
            String pass = AppConfig.getString("pass");
            et_phone.setText(user);
            et_pass.setText(pass);
            cb_pass.setChecked(true);
        }
        cb_check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked) {
                    et_pass.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    et_pass.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });

        cb_pass.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked) {
                    cb_pass.setChecked(true);
                } else {
                    cb_pass.setChecked(false);
                }
            }
        });

    }

    @Override
    protected void initData() {
        super.initData();
    }
    @OnClick({R.id.ll_back,R.id.tv_register,R.id.tv_forgetPass,R.id.tv_login,R.id.iv_qq,R.id.iv_weixin})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_back:
                onBackPressed();
                break;
            case R.id.iv_qq:
                SimpleHUD.showLoadingMessage(this,"",true);
                flag = 1;
                Platform qqZone = ShareSDK.getPlatform(QQ.NAME);
                doAuthorize(qqZone);
                break;
            case R.id.iv_weixin:
                SimpleHUD.showLoadingMessage(this,"",true);
                flag = 2;
                Platform weixn = ShareSDK.getPlatform(Wechat.NAME);
                doAuthorize(weixn);
                break;
            case R.id.tv_login:
                String phone = et_phone.getText().toString();
                String pass = et_pass.getText().toString();
                if(TextUtils.isEmpty(phone)){
                    ToastUtil.show(this,"请输入手机号");
                    return;
                }else if(TextUtils.isEmpty(pass)){
                    ToastUtil.show(this,"请输入密码");
                    return;
                }
                login(phone,pass);
                break;
            case R.id.tv_register:
                intent = new Intent(this,IdentifyActivity.class);
                intent.putExtra("type",0);
                startActivity(intent);
                break;
            case R.id.tv_forgetPass:
                intent = new Intent(this,RegisterActivity.class);
                intent.putExtra("type",2);
                startActivity(intent);
                break;
        }
    }

    public void login(final String phone, final String pwd){
        Map<String,String> map = new HashMap<>();
        map.put("action", ActionUtil.user_login_get);
        map.put("phone", phone);
        map.put("pwd", pwd);
        NetManager.getInstance().request(this, map, true, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                try {
                    AppConfig.saveString("user", phone);
                    AppConfig.saveString("pass", pwd);
                    JSONObject jsonObject = new JSONObject(result);
                    int role = jsonObject.optInt("role");
                    String state = jsonObject.optString("state_check");
                    String userid = jsonObject.optString("userid");
                    AppConfig.saveInt("card",role);
                    AppConfig.saveString("state_check",state);
                    AppConfig.saveString("userid",userid);
                    initChat(userid,jsonObject.optString("pwd"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onComplete(Platform platform, int i, final HashMap<String, Object> hashMap) {
        SimpleHUD.dismiss();
        ThirdLoginBean pBean=new ThirdLoginBean();
        if(flag == 1){
            pBean.setuID(platform.getDb().getUserId());

        }else {
            pBean.setuID(platform.getDb().get("openid"));
        }
        pBean.setuNickName(platform.getDb().getUserName());
        pBean.setuPhoto(platform.getDb().getUserIcon());
        Message msg = handler.obtainMessage();
        msg.obj =pBean;
        handler.sendMessage(msg);
    }

    @Override
    public void onError(Platform platform, int i, final Throwable throwable) {
         runOnUiThread(new Runnable() {
             @Override
             public void run() {
                 SimpleHUD.dismiss();
                 throwable.printStackTrace();
                 ToastUtil.show(LoginActivity.this,"第三方登录失败");
             }
         });
    }

    @Override
    public void onCancel(Platform platform, int i) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                SimpleHUD.dismiss();
                ToastUtil.show(LoginActivity.this,"第三方登录取消");
            }
        });
    }

    /**
     * 授权的代码
     */
    public void doAuthorize(Platform platform) {
        if (platform != null) {
            platform.setPlatformActionListener(this);
            if (platform.isAuthValid()) {
                platform.removeAccount(true);
                return;
            }
            platform.SSOSetting(true);
            platform.authorize();
        }
    }

    public void userThirdloginSet(ThirdLoginBean thirdLoginBean, final int flag){
        Map<String,String> map = new HashMap<>();
        map.put("action",ActionUtil.user_thirdlogin_set);
        if(flag == 1){
            map.put("qq",thirdLoginBean.getuID());
            map.put("qqname",thirdLoginBean.getuNickName());
            map.put("photo",thirdLoginBean.getuPhoto());
        }else if(flag == 2){
            map.put("weixinid",thirdLoginBean.getuID());
            map.put("weixinname",thirdLoginBean.getuNickName());
            map.put("photo",thirdLoginBean.getuPhoto());
        }
        NetManager.getInstance().request(this, map, false, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                try {
                    JSONObject object = new JSONObject(result);
                    String userid = object.optString("userid");
                    if(TextUtils.isEmpty(object.optString("phone"))){
                        ToastUtil.show(LoginActivity.this,msg);
                        AppConfig.saveString("userid",userid);
                        intent = new Intent(LoginActivity.this,BindPhoneActivity.class);
                        intent.putExtra("thirdlogintype",flag+"");
                        startActivity(intent);
                    }else {
                        int role = object.optInt("role");
                        String state = object.optString("state_check");
                        AppConfig.saveInt("card",role);
                        AppConfig.saveString("state_check",state);
                        AppConfig.saveString("userid",userid);
                        initChat(userid,object.optString("pwd"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isLocation) {
        } else {
            LocationUtils.locateDelegateArrayList.add(this);
            LocationUtils.startLocation();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        LocationUtils.locateDelegateArrayList.remove(this);
        LocationUtils.stopLocation();
        isLocation = true;
    }

    @Override
    public void onLocateSuccess(BDLocation location) {

    }

    @Override
    public void onLocateFailed() {
        ToastUtil.show(this,"定位失败");
    }

    /**
     * 阿里百川的聊天
     */
    private void initChat(String userid,String pwd) {
            Log.e("TAG","userid"+userid+"pwd---"+pwd);
            YWIMKit mIMKit = YWAPI.getIMKitInstance(userid, AppConfig.APP_KEY);
            IYWLoginService loginService = mIMKit.getLoginService();
            YWLoginParam loginParam = YWLoginParam.createLoginParam(userid,pwd);
            loginService.login(loginParam, new IWxCallback() {
                @Override
                public void onSuccess(Object... arg0) {
                    ToastUtil.show(LoginActivity.this, "登录成功");
                    startActivity(new Intent(LoginActivity.this,MainActivity.class));
                    finish();
                }
                @Override
                public void onProgress(int arg0) {}
                @Override
                public void onError(int errCode, String description) {
                    //如果登录失败，errCode为错误码,description是错误的具体描述信息
                    Log.e("TAG","description----"+description+"errCode-----"+errCode);
                }
            });
        }

    @Override
    public void onBackPressed() {
        AppManager.getAppManager().AppExit();
        super.onBackPressed();
    }
}
